const { FileUtil } = require('../../regist')
const path = require('path');
const moment = require("moment")
const {File} = FileUtil;


//生命周期服务
class LifeCircleService {


	constructor(fsPath){
		this.data = {};
		this.file = new File(fsPath)
		if(!this.file.exist()){
			this.file.touch();
			this.update({lastOrderStamp:0,totalAmount:0,totalCount:0,price:{},balance:0}).flush();
		}else{
			this.data = this.file.getObject();
		}
	}

	update(data){
		this.data = {...this.data,...data}
		return this;
	}

	flush(){
		this.file.setObject(this.data).write();
		return this;
	}

	getLastOrderTime(){
		return this.data.lastOrderStamp;
	}

	addAmount(amount,price,balance){

		const updateData = {
			totalAmount:this.data.totalAmount+amount,
			lastOrderStamp:moment().valueOf(),
			lastOrderDate:moment().format('YYYY-MM-DD HH:mm'),
			balance,
			totalCount:this.data.totalCount+1,
			price:{...this.data.price,...price}
		}

		this.update(updateData).flush();
	}

}

//读取json文件
const ReadJsonFile = filePath => {
	const file = new File(filePath);
	if(!file.exist()){
		throw `config file:${filePath} not exist! please add before launch`
	}
	return file.getObject();
}

const ReadJsonFileList = (pathPrefix,fileNameList) => {
	return fileNameList.reduce((s,v)=>{
		s[v] = ReadJsonFile(path.join(pathPrefix,`${v}.json`))
		return s;
	},{})
}


module.exports = {LifeCircleService,ReadJsonFile,ReadJsonFileList}